package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMappe;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMappe userMappe;
    public static final String GRANT_TYPE="authorization_code";
    public static final String WX_LOGIN="https://api.weixin.qq.com/sns/jscode2session";
    @Override
    public User wxlogin(UserLoginDTO userLoginDTO) {

        Map<String, String> loginmap=new HashMap<>();
        loginmap.put("appid",weChatProperties.getAppid());
        loginmap.put("secret",weChatProperties.getSecret());
        loginmap.put("js_code",userLoginDTO.getCode());
        loginmap.put("grant_type",GRANT_TYPE);
       String json= HttpClientUtil.doGet(WX_LOGIN,loginmap);
        JSONObject jsonObject= JSON.parseObject(json);
        log.info(String.valueOf(jsonObject));
        String openid=jsonObject.getString("openid");
        String sessionKey = jsonObject.getString("session_key");
        log.info(sessionKey);
        if(openid==null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        User loginuser= userMappe.getbyopenid(openid);

        if(loginuser==null ){
         loginuser= User.builder().openid(openid).sessionKey(sessionKey).createTime(LocalDateTime.now()).build();
        userMappe.insert(loginuser);
        }

        return loginuser;
    }
}
